package servlet;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.IOUtils;

import javax.servlet.Servlet;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.List;

@WebServlet("/upload")
public class UploadServlet extends HttpServlet {
    private static  final  String SAVE_DIR = "D:\\JavaWeb\\WebDemo4\\upload";
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        if(ServletFileUpload.isMultipartContent(req)){
//            如果是文件上传的请求
//            创建一个磁盘文件项工厂
            DiskFileItemFactory factory = new DiskFileItemFactory();
            factory.setDefaultCharset("utf-8");
//            设置临时文件的存储位置
            factory.setRepository(new File("java.io.tmpdir"));
//            设置每个文件项的最大大小为4096KB，超过就会使用临时文件进行保存到临时文件中
            factory.setSizeThreshold(4096 * 1024);
//            创建文件上传的对象
            ServletFileUpload upload = new ServletFileUpload(factory);
//            设置上传文件的最大大小为5MB
            upload.setFileSizeMax(5*1024*1024);
//            设置总上传数据的最大大小为50MB
            upload.setSizeMax(50*1024*1024);
            upload.setHeaderEncoding("UTF-8");
            try {
//                开始解析请求，得到文件项
                List<FileItem> fileItems = upload.parseRequest(req);
                for (FileItem fileItem : fileItems) {
                    if(fileItem.isFormField()){// 判断是否是普通表单字段
//                        打印参数名和参数值
                        System.setOut(new PrintStream(System.out,true,"UTF-8"));
                        System.out.println(fileItem.getFieldName()+"=>"+fileItem.getString("UTF-8"));
                    }else{//上传的是文件
                        File dir = new File(SAVE_DIR);
                        if(!dir.exists()){
                            dir.mkdirs();
                        }
//                        创建保存文件的对象
                        File saveFile = new File(dir,fileItem.getName());
//                        获取上传文件的输入流
                        InputStream is = fileItem.getInputStream();
                        OutputStream os = new FileOutputStream(saveFile);
                        IOUtils.copy(is,os);//将输入流中的信息拷贝到输出流中
//                        关闭流
                        IOUtils.closeQuietly(is);
                        IOUtils.closeQuietly(os);
                    }
                }
                resp.setContentType("text/html;charset=utf-8");
                resp.setCharacterEncoding("utf-8");
                resp.getWriter().print("上传文件成功");
            } catch (FileUploadException e) {
                resp.setContentType("text/html;charset=utf-8");
                resp.setCharacterEncoding("utf-8");
                resp.getWriter().print("上传文件失败");
                throw new RuntimeException(e);
            }
        }else{
            throw new RuntimeException("请求头中未发现multipart/form-data");
        }
    }
}
